package com.madding.shared.net.socket;

import java.io.*;
import java.net.*;

public class Client {

    Socket             requestSocket;

    ObjectOutputStream out;
    ObjectInputStream  in;
    BufferedReader     br;
    InputStreamReader  isr;

    String             message;

    Client(){
        isr = new InputStreamReader(System.in);
        br = new BufferedReader(isr);
    }

    void run() {
        try {
            // 1. creating a socket to connect to the server
            requestSocket = new Socket("localhost", 2004);
            System.out.println("Connected to localhost in port 2004");
            // 2. get Input and Output streams
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());
            // 3: Communicating with the server
            do {
                try {
                    displayMessage();

                    inputMessage();

                    sendMessage();
                } catch (ClassNotFoundException classNot) {
                    System.err.println("data received in unknown format");
                }
            } while (!message.equals("bye"));
        } catch (UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host!");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            // 4: Closing connection
            try {
                in.close();
                out.close();
                isr.close();
                br.close();
                requestSocket.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    void displayMessage() throws IOException, ClassNotFoundException {
        message = (String) in.readObject();
        System.out.println("server>" + message);
    }

    void inputMessage() throws IOException {
        System.out.print("client>");
        message = br.readLine();
    }

    void sendMessage() {
        try {
            out.writeObject(message);
            out.flush();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    public static void main(String args[]) {
        Client client = new Client();
        client.run();
    }
}
